﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace OPCService.Utils
{
    class ConfigHelper
    {
        public static string ReadConfig(String key)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap();  //用于定义自定义的配置文件路径，可以指定应用程序的配置文件路径，而不是使用默认的配置文件。
            file.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + "Setting.config";
            Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

            var myApp = (AppSettingsSection)config.GetSection("appSettings");
            return myApp.Settings[key]?.Value;

        }

        public static string ReadFieldConfig(String key)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap();
            file.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + "Setting.config";
            Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
            config.EvaluationContext.GetSection("PostSetting");
            var myApp = config.Sections.Get("PostSetting");
            return myApp.ElementInformation.ToString();

        }



        public static string WriteConfig(string key, string val)
        {
            ExeConfigurationFileMap file = new ExeConfigurationFileMap();
            file.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + "Setting.config";
            Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);

            var myApp = (AppSettingsSection)config.GetSection("appSettings");
            myApp.Settings[key].Value = val;
            config.Save();
            return val;

        }
    }
}
